//
//  CZUserAccountViewModel.swift
//  iOSWeibo10
//
//  Created by 李伟鹏 on 16/5/12.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZUserAccountViewModel: NSObject {
    
    static let sharedInstance:CZUserAccountViewModel = CZUserAccountViewModel()
    
    let userAccountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    var userAccount: CZUserAccount?
    
    var isUserLogin:Bool {
        get{
            return userAccount != nil 
        }
    }
    
    override init() {
        super.init()
        userAccount = loadUserAccount()
    }
    
    func loadAccessToken(code: String, callBack:(error:NSError?) -> ()){
        let urlString = "oauth2/access_token"
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri": redirect_uri
        ]
        CZNetworkTool.sharedInstance.request(RequestMethod.POST, URLString: urlString, parameters: parameters, success: { (task, responseObject) -> Void in
            if let result = responseObject as?[String: AnyObject]{
                let userAccount = CZUserAccount(dict: result)
                NSKeyedArchiver.archiveRootObject(userAccount, toFile: self.userAccountPath)
                self.userAccount = userAccount
                self.saveUserAccount()
                callBack(error: nil)
            }else {
                CZPrint(items: "返回数据转字典失败了")
            }
            }, failure: { (task, error) -> Void in
                CZPrint(items: "失败了: \(error)")
                callBack(error: error)
                
        })
    }
    
    private func saveUserAccount(){
        if let account = userAccount{
            NSKeyedArchiver.archiveRootObject(account, toFile: self.userAccountPath)
        }
    }
    
    func loadUserAccount() -> CZUserAccount?{
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(self.userAccountPath) as? CZUserAccount{
            if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending{
                return userAccount
            }else{
                return nil
            }
        }else{
            return nil
        }
    }
    
    func loadUserInfo(loadUserInfoCallback: () -> ()){
        guard let access_token = userAccount?.access_token else{
            CZPrint(items: "access_token没有值")
            return
        }
        guard let uid = userAccount?.uid else{
             CZPrint(items: "uid没有值")
            return
        }
        let urlString = "2/users/show.json"
        let parameters = [
            "access_token" : access_token,
            "uid" : uid
        ]
        CZNetworkTool.sharedInstance.request(RequestMethod.GET, URLString: urlString, parameters: parameters, success: { (_, responObject) -> Void in
            if let result = responObject as? [String:AnyObject]{
                let screen_name = result["screen_name"] as? String
                let avatar_large = result["avatar_large"] as? String
                self.userAccount?.screen_name = screen_name
                self.userAccount?.avatar_large = avatar_large
                self.saveUserAccount()
               loadUserInfoCallback()
                
            }
            }) { (_,  error) -> Void in
                CZPrint(items: "获取用户信息出错了: \(error)")
        }
    }
    
}
